//
//  JJVoicePlayHelper.swift
//  swiftProject
//
//  Created by yangjian on 2021/12/8.
//

import UIKit
import AVFAudio

class JJVoicePlayHelper: NSObject,AVAudioPlayerDelegate {
//    private static let jj = JJVoicePlayHelper.init()
//    class func shared() -> JJVoicePlayHelper{
//        return jj;
//    }
    static let share = JJVoicePlayHelper()
//    private init(){}

    var path = ""
    var player : AVAudioPlayer!
    var completion : ((NSError?) ->Void) = {error in }
    var msgCellModel : MsgCellBaseModel?
    func play(model:MsgCellBaseModel,completion:@escaping((NSError?) ->Void)) {
        guard let body = model.message.body as? EMVoiceMessageBody else {
            return
        }
        var playing = try? model.rx_voicePlaying.value()
        guard let playing else {
            return
        }
        if playing {
            self.stop(error: nil)
        }else{
            model.rx_voicePlaying.onNext(true)
            self.play(path: body.localPath,completion: completion)
        }
        self.msgCellModel = model
    }
    
    func play(path:String,completion:@escaping((NSError?) ->Void)) {
        self.stop(error: NSError(domain: "正常停止", code: 0))
        
        self.path = file_fetchVoickWAVFilePath(filePath: path)
        self.completion = completion
        
        if self.path.count < 1 {
            stop(error: NSError.init(domain: "AVAudioPlayer.init(contentsOf", code: 500, userInfo: [:]))
            return
        }
        do {
            try self.player = AVAudioPlayer.init(contentsOf: URL.init(fileURLWithPath: self.path))
        } catch {
            print(error)
            stop(error: NSError.init(domain: "AVAudioPlayer.init(contentsOf", code: 500, userInfo: [:]))
            return
        }
        self.player.delegate = self
        if self.player.prepareToPlay() {
            let audioSession = AVAudioSession.sharedInstance()
            do {
                try audioSession.setCategory(.playback)
            } catch {
                print(error)
                stop(error: NSError.init(domain: "audioSession.setCategory", code: 500, userInfo: [:]))
                return
            }
        }
        
        if !self.player.play() {
            stop(error: NSError.init(domain: "player.play()", code: 500, userInfo: [:]))
            return
        }
    }
    
    func stop(error : NSError?){
        if let model = self.msgCellModel {
            model.rx_voicePlaying.onNext(false)
            self.msgCellModel = nil
        }
        completion(error)
        if self.player != nil {
            self.player.delegate = nil
            self.player.stop()
            self.player = nil
        }
        self.completion = {error in }
        self.path = ""
    }
}

extension JJVoicePlayHelper {
    func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
        self.stop(error: nil)
    }
    func audioPlayerDecodeErrorDidOccur(_ player: AVAudioPlayer, error: Error?) {
        self.stop(error: NSError.init(domain: "audioPlayerDecodeErrorDidOccur", code: 500, userInfo: [:]))
    }
}
